import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/update_book")
public class UpdateBook extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

        String number = request.getParameter("number");
        String name = request.getParameter("name");
        String author = request.getParameter("author");

        if (number == null || number.isEmpty() || name == null || name.isEmpty() || author == null || author.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"status\":\"error\", \"message\":\"All fields are required.\"}");
            return;
        }

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement("UPDATE t_book SET name = ?, author = ? WHERE number = ?")) {
            stmt.setString(1, name);
            stmt.setString(2, author);
            stmt.setString(3, number);
            int rowsAffected = stmt.executeUpdate();

            if (rowsAffected > 0) {
                response.setContentType("application/json");
                response.getWriter().write("{\"status\":\"success\", \"message\":\"Book updated successfully.\"}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("{\"status\":\"error\", \"message\":\"Error updating book.\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"status\":\"error\", \"message\":\"Database error: " + e.getMessage() + "\"}");
        }
    }

    private Connection getConnection() throws SQLException {
        String jdbcUrl = "jdbc:mysql://113.44.148.207:3306/linux_exam";
        String jdbcUsername = "root";
        String jdbcPassword = "1qaz@WSX#EDC";
        return DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
    }
}

